﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharedGenomics.Core;

namespace SharedGenomics.DataAccess
{
    public class InvalidDuplicateGenotypeDataValidationMessage : ValidationMessage
    {
        private List<int> _invalidRowIndices;

        public InvalidDuplicateGenotypeDataValidationMessage(string columnName, int columnIndex, int dupColumnIndex, ValidationMessageSeverity severity)
            : base(String.Empty, severity)
        {
            columnName.ThrowIfNull("columnName");
            this.ColumnName = columnName;
            this.ColumnIndex = columnIndex;
            this.DuplicateColumnIndex = dupColumnIndex;

            this._invalidRowIndices = new List<int>();
        }

        public override string Message
        {
            get
            {
                return this.GetSummaryMessageBuilder().ToString();
            }
        }

        public override string ExtendedMessage
        {
            get
            {
                StringBuilder builder = this.GetSummaryMessageBuilder();

                if (this._invalidRowIndices.Count > 0)
                {
                    builder.AppendLine().AppendLine("The following rows are different:");

                    //add a line for each invalid row to the builder
                    this._invalidRowIndices.Select(i => i + 1).Aggregate(builder, (b, ri) => b.AppendLine(ri.ToString())).ToString();
                }

                return builder.ToString();
            }
        }

        private StringBuilder GetSummaryMessageBuilder()
        {
            string baseMessage = String.Format("Columns {0} and {1} are both called '{2}'.", this.ColumnIndex + 1, this.DuplicateColumnIndex + 1, this.ColumnName);
            StringBuilder builder = new StringBuilder(baseMessage);

            if (this._invalidRowIndices.Count > 0)
            {
                builder.AppendFormat(" The data differs for {0} loci - both columns have been removed from the data.", this._invalidRowIndices.Count);
            }

            return builder;
        }

        public IEnumerable<int> InvalidRowIndices
        {
            get { return this._invalidRowIndices; }
            set
            {
                this._invalidRowIndices.AddRange(value ?? Enumerable.Empty<int>());
            }
        }

        private int ColumnIndex { get; set; }
        private string ColumnName { get; set; }
        private int DuplicateColumnIndex { get; set; }
        private string DuplicateColumnName { get; set; }
    }
}
